import 'dart:async';
import 'dart:io';

import 'package:audio_session/audio_session.dart';
import 'package:brage/brage.dart';
import 'package:fate_blind_box/network/http_config.dart';
import 'package:fate_blind_box/routes/app_pages.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/ui/guide/download_new.dart';
import 'package:fate_blind_box/ui/login/login_by_pwd.dart';
import 'package:fate_blind_box/ui/main/navigator.dart';
import 'package:fate_blind_box/ui/user/invite3.dart';
import 'package:fate_blind_box/utils/privte_dialog.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:just_audio/just_audio.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'config/event_bus.dart';
import 'config/event_keys.dart';

final GlobalKey<NavigatorState> navKey = GlobalKey<NavigatorState>();
final player = AudioPlayer();
bool? privacyPolicyDialog = false;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  if (Provider.memberId.isEmpty) {
    Provider.memberId = await Provider.getCache("memberId");
  }
  if (HttpConfig.token.isEmpty) {
    HttpConfig.token = await Provider.getCache("token");
  }
  if (!kIsWeb) {
    //初始化环信
    await _initSDK();
  }

  SharedPreferences prefs = await SharedPreferences.getInstance();
  privacyPolicyDialog = prefs.getBool('PrivacyPolicyDialog');
  // 以下两行 设置android状态栏为透明的沉浸。写在组件渲染之后，是为了在渲染后进行set赋值，覆盖状态栏，写在渲染之前MaterialApp组件会覆盖掉这个值。
  runApp(defaultApp());

  if (Platform.isAndroid) {
    SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: Brightness.dark);
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  }
  //添加消息监听
  _addChatListener();
}

void _addChatListener() {
  // 添加消息状态变更监听
  EMClient.getInstance.chatManager.addMessageEvent(
      // ChatMessageEvent 对应的 key。
      "YXA6hl6vye2MTQOb2k-1mAKAiA",
      ChatMessageEvent());

  // 添加收消息监听
  EMClient.getInstance.chatManager.addEventHandler(
    // EMChatEventHandler 对应的 key。
    "YXA6hl6vye2MTQOb2k-1mAKAiA",
    EMChatEventHandler(
      onMessagesReceived: (messages) async {
        player.setAsset('images/music_reveice.mp3');
        final session = await AudioSession.instance;
        session.configure(const AudioSessionConfiguration.music());
        player.play();
        EMClient.getInstance.chatManager.getUnreadMessageCount().then((value) {
          Brage().setIOSBrage(brage: value);
          EventBus.instance
              .commit(eventName: EventKeys.chatUpdateBadge, data: value);
        });
        for (var msg in messages) {
          switch (msg.body.type) {
            case MessageType.TXT:
              {
                EMTextMessageBody body = msg.body as EMTextMessageBody;
                // _addLogToConsole(
                //   "收到文字消息: ${body.content}, from: ${msg.from}",
                // );
              }
              break;
            case MessageType.IMAGE:
              {
                // _addLogToConsole(
                //   "收到图片信息, from: ${msg.from}",
                // );
              }
              break;
            case MessageType.VIDEO:
              {
                // _addLogToConsole(
                //   "收到视频信息, from: ${msg.from}",
                // );
              }
              break;
            case MessageType.LOCATION:
              {
                // _addLogToConsole(
                //   "收到位置信息, from: ${msg.from}",
                // );
              }
              break;
            case MessageType.VOICE:
              {
                // _addLogToConsole(
                //   "收到语音留言, from: ${msg.from}",
                // );
              }
              break;
            case MessageType.FILE:
              {
                // _addLogToConsole(
                //   "收到图片信息, from: ${msg.from}",
                // );
              }
              break;
            case MessageType.CUSTOM:
              {
                // _addLogToConsole(
                //   "接受自定义信息, from: ${msg.from}",
                // );
              }
              break;
            case MessageType.CMD:
              {
                // 当前回调中不会有 CMD 类型消息，CMD 类型消息通过 `EMChatEventHandler#onCmdMessagesReceived` 回调接收
              }
              break;
          }
        }
      },
    ),
  );
}

//初始化sdk
Future? _initSDK() async {
  EMOptions options = EMOptions(
    appKey: "1168230328160038#ouranyj",
    // appKey: "1168230328160038#demo",
    autoLogin: true,
  );
  options.enableAPNs('ouranyujian_release');
  print('环信注册成功');

  options.enableOppoPush(
      'd367e5ea67334b2eb9e8ac563a0cddce', '0102b4eec21c446cbcfa54bf666aff86');
  options.enableVivoPush();
  // options.enableMiPush('2882303761520263769', '5222026312769');
  options.enableHWPush();

  await EMClient.getInstance.init(options);
  // 通知 SDK UI 已准备好。该方法执行后才会收到 `EMChatRoomEventHandler`、`EMContactEventHandler` 和 `EMGroupEventHandler` 回调。
  await EMClient.getInstance.startCallback();
}

Widget defaultApp() {
  return RefreshConfiguration(
    headerBuilder: () => const WaterDropHeader(),
    // 配置默认头部指示器,假如你每个页面的头部指示器都一样的话,你需要设置这个
    footerBuilder: () => const ClassicFooter(),
    // 配置默认底部指示器
    headerTriggerDistance: 80.0,
    // 头部触发刷新的越界距离
    springDescription:
        const SpringDescription(stiffness: 170, damping: 16, mass: 1.9),
    // 自定义回弹动画,三个属性值意义请查询flutter api
    maxOverScrollExtent: 100,
    //头部最大可以拖动的范围,如果发生冲出视图范围区域,请设置这个属性
    maxUnderScrollExtent: 0,
    // 底部最大可以拖动的范围
    enableScrollWhenRefreshCompleted: true,
    //这个属性不兼容PageView和TabBarView,如果你特别需要TabBarView左右滑动,你需要把它设置为true
    enableLoadingWhenFailed: true,
    //在加载失败的状态下,用户仍然可以通过手势上拉来触发加载更多
    hideFooterWhenNotFull: false,
    // Viewport不满一屏时,禁用上拉加载更多功能
    enableBallisticLoad: true,
    child: ScreenUtilInit(
        designSize: const Size(390, 844),
        minTextAdapt: true,
        splitScreenMode: true,
        builder: (context, child) {
          ScreenUtil.init(context);
          return GetMaterialApp(
            title: '都肆商圈',
            localizationsDelegates: const [
              GlobalMaterialLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
            ],
            supportedLocales: const [
              Locale('zh', 'CH'),
              Locale('en', 'US'),
            ],
            locale: const Locale('zh'),
            debugShowCheckedModeBanner: false,
            navigatorKey: navKey,
            initialRoute: "/",
            navigatorObservers: [AppPages.observer],
            getPages: AppPages.routes,
            routes: {
              "/share": (context) => const Invite3Ui(),
              "/download": (context) => const DownloadAppUiNew(),
              "/login": (context) => const LoginByPwd(),
              "/invite": (context) => const LoginByPwd(),
              "/main": (context) => AppMain(),
            },
            theme: ThemeData(
              primaryColor: ThemeColor.mainColor,
              shadowColor: ThemeColor.shadowColor,
              appBarTheme: const AppBarTheme(
                iconTheme: IconThemeData(color: Colors.black),
                actionsIconTheme: IconThemeData(color: Colors.black),
                backgroundColor: Colors.white,
              ),
            ),
            home: privacyPolicyDialog == true
                ? mainPage()
                : const PrivacyPolicyDialog(),
            // builder: EasyLoading.init(),
            builder: (context, widget) {
              return MediaQuery(
                //设置文字大小不随系统设置改变
                data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
                child: FlutterEasyLoading(
                    child: InkWell(
                        onTap: () => _hideKeyboard(context), child: widget)),
              );
            },
          );
        }),
  );
}

void _hideKeyboard(BuildContext context) {
  FocusScopeNode currentFocus = FocusScope.of(context);
  if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
    FocusManager.instance.primaryFocus?.unfocus();
  }
}

Widget mainPage() {
  return HttpConfig.token.isEmpty ? const LoginByPwd() : AppMain();
}

/// 测试修改git 提交
